<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="inet.db.tennis.TennisChampion"%>
<%@page import="inet.db.tennis.TennisMatch"%>
<%@page import="inet.util.DateTime"%>
<%@page import="inet.db.tennis.buffer.TennisBuffer"%>
<%@page import="inet.db.tennis.TennisPhase"%>
<%@page import="java.math.BigDecimal"%>
<%@page import="inet.db.tennis.TennisRound"%>
<%@page import="inet.db.tennis.TennisPlayer"%>
<%@page import="inet.util.StringTool"%>
<jsp:useBean id="tennisChampionDAO" class="inet.db.tennis.TennisChampionDAO" scope="session"/>
<jsp:useBean id="tennisMatchDAO" class="inet.db.tennis.TennisMatchDAO" scope="session"/>
<jsp:useBean id="tennisPhaseDAO" class="inet.db.tennis.TennisPhaseDAO" scope="session"/>
<jsp:useBean id="tennisRoundDAO" class="inet.db.tennis.TennisRoundDAO" scope="session"/>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Tạo trận đấu cho vòng kế tiếp</title>
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/reset.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/text.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/grid.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/layout.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/nav.css" media="screen" />
    <!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
    <!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
    <!--<link href="<%= request.getContextPath() %>/admin/tennis/css/table/demo_page.css" rel="stylesheet" type="text/css" />-->
    <link href="<%= request.getContextPath() %>/admin/tennis/css/style.css" rel="stylesheet" type="text/css" />
    <!-- BEGIN: load jquery -->
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="<%= request.getContextPath() %>/admin/tennis/text/javascript" src="js/jquery-ui/jquery.ui.core.min.js"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.accordion.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.effects.core.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.effects.slide.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.mouse.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.sortable.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/table/jquery.dataTables.min.js" type="text/javascript"></script>
    <!-- END: load jquery -->
    <script type="text/javascript" src="<%= request.getContextPath() %>/admin/tennis/js/table/table.js"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/setup.js" type="text/javascript"></script>
    <script src="score.js"></script>
    <script src="status.js"></script>
    <%--<script type="text/javascript">
        $(document).ready(function () {
            setupLeftMenu();
            var oTable = $('.datatable').dataTable();
            oTable.fnSort( [ [1,'asc'] ] );
			setSidebarHeight();
        });
    </script>
    --%>
    <script type="text/javascript">
    	function f_delete_select_item() {
    		document.formListMatch.action.value = 'delete_selected';
    		document.formListMatch.submit();
    	}
    	function f_delete_item(item_del) {
    		document.formListMatch.item_del.value = item_del; 
    		document.formListMatch.action.value = 'delete_item';
    		document.formListMatch.submit();
    	}
    </script>
</head>
<body>
    <div class="container_12">
        <%@ include file="../include/header.jsp" %>
        <% 
           request.setCharacterEncoding("UTF-8");
           response.setCharacterEncoding("UTF-8");
		   String sChampionCode = request.getParameter("championCode");
		   String sPhase = request.getParameter("slbPhase");
		   String sRound = request.getParameter("slbRound");
		
			//Vector<TennisMatch> vTennisMatch = tennisMatchDAO.findAll();
			TennisChampion championSelected = null;
			if(sChampionCode != null) {
				championSelected = TennisBuffer.getChampionFromCode(sChampionCode);
				if(championSelected == null) {
					championSelected = TennisBuffer.reloadChampion(sChampionCode);
				}
			}
			BigDecimal phaseId = null;
			String currRound = "";
			
			String sAction = request.getParameter("action");
			String sMessageErr = "";
            String sMessageOk = "";
            String sMessageWarning = "";
            String sNextRound = request.getParameter("slbNextRound");
			if("CREATE_SCHEDULE".equals(sAction)) {
				// Tạo lịch cho vòng đấu tiếp theo
				if(sNextRound != null && !"0".equals(sNextRound)) {
					// Check và thông báo cho người dùng biết vòng sNextRound đã có bao nhiêu trận rồi
					if(StringTool.isNumberic(sPhase)) {
						phaseId = new BigDecimal(sPhase);
					}
					int totalMatchNext = tennisMatchDAO.countMatchInRoundOfChampion(sChampionCode, sNextRound, phaseId);
					if(totalMatchNext > 0) {
						sMessageWarning = "Đã có "+ totalMatchNext +" trận đấu của vòng " + sNextRound;
					} else { // end check
						if(currRound == null || "".equals(currRound)) {
							currRound = sRound;
						}
						Vector<TennisMatch> vMatchSchedule = tennisMatchDAO.findMatchListInRoundOfChampion(sChampionCode, currRound, phaseId);
						if (vMatchSchedule != null && !vMatchSchedule.isEmpty()) {
						    if(vMatchSchedule.size() % 2 == 0) { // Số trận đấu phải là chẵn ==> để tạo đủ cặp đấu
						        TennisMatch match = null;
						        // Get max stt các trận đấu của vòng kế tiếp
						        int maxStt = tennisMatchDAO.getMaxSTT(championSelected.getCurrentPhase(), sNextRound);
						        // Khởi tạo các giá trị mặc định cho các trận đấu của vòng kế tiếp.
						        TennisMatch matchCreated = new TennisMatch();
						        matchCreated.setChampionCode(championSelected.getCode());
						        matchCreated.setPhaseId(championSelected.getCurrentPhase());
						        matchCreated.setRound(sNextRound);
						        matchCreated.setTotalSet(championSelected.getTotalSet());
						        int i = 1;
						        
						        BigDecimal matchIdPrevious = BigDecimal.ZERO;
						        BigDecimal matchIdNext = BigDecimal.ZERO;
						        for (Iterator it = vMatchSchedule.iterator(); it.hasNext(); i++) {
						           match = (TennisMatch) it.next();
						           if(match == null) continue;
						           if(i % 2 == 0) {
						               maxStt += 1;
						               matchCreated.setStt(maxStt);
						               matchIdNext = tennisMatchDAO.insertRowTennisMatch(matchCreated);
						               if (!matchIdNext.equals(BigDecimal.ZERO)) {
						                   tennisMatchDAO.updateMapMatchId(matchIdPrevious, matchIdNext);
						                   tennisMatchDAO.updateMapMatchId(match.getId(), matchIdNext);
						                   sMessageOk = "Tạo thành công các cặp đấu cho vòng tiếp theo";
						               } else {
						                   sMessageErr = "Xảy ra lỗi khi tạo cặp, "+ match.getId()+ " vs " + matchIdPrevious;
						                   break;
						               }
						           } else {
						               // Id của trận đấu trước đó (trận đấu có thứ tự lẻ)
						               matchIdPrevious = match.getId();
						           }
						        }
						    } else {
						        sMessageWarning = "Số trận đấu của vòng "+ currRound + " đang bị lẻ.";
						    }
						} else {
							sMessageWarning = "Không tìm thấy danh sách trận đấu của vòng "+ currRound;
						}
					}
				} else {
				    sMessageWarning = "Chưa CHỌN vòng đấu tiếp theo";
				}
			} else if ("UPDATE_STT".equals(sAction)) {
				String[] listMatchId = request.getParameterValues("txt_match_id");
				String[] listSTT = request.getParameterValues("txtSTT");
				boolean isOk = tennisMatchDAO.updateField(listMatchId, listSTT, "STT", true);
				if(isOk) {
					sMessageOk = "Cập nhật thứ tự trận đấu thành công";
				} else {
					sMessageErr = "Xảy ra lỗi khi cập nhật thứ tự trận đấu";
				}
			}
			// Delete selected rows
    		else if(sAction != null && "delete_selected".equals(sAction)) {
    			String[] selected = request.getParameterValues("chkID");
    			if (selected != null && selected.length > 0) {
		            for (int i = 0; i < selected.length; i++) {
						tennisMatchDAO.deleteRow(new BigDecimal(selected[i]));
		            }
		        }
    		} else if(sAction != null && "delete_item".equals(sAction)) {
    			String itemSelected = request.getParameter("item_del");
    			if(itemSelected != null && StringTool.isNumberic(itemSelected)) {
    				tennisMatchDAO.deleteRow(new BigDecimal(itemSelected)); 
    			}
    		}
        %>
        <div class="grid_10">
        	<% 
        		if(championSelected != null) { 
	        		// Gán giá trị cho phaseId
					if(sPhase != null && StringTool.isNumberic(sPhase) && !"0".equals(sPhase)) {
						phaseId = new BigDecimal(sPhase);
					} else {
						phaseId = championSelected.getCurrentPhase();
					}
					// Gán giá trị cho round
					if(sRound != null && !"0".equals(sRound)) {
						currRound = sRound;
					} else {
						currRound = championSelected.getCurrentRound();
					}
					int currRoundNo = 0; // No của vòng đấu hiện tại
					Vector<TennisMatch> vMatch = null;
					vMatch = tennisMatchDAO.findMatchListInRoundOfChampion(sChampionCode, currRound, phaseId);
        	%>
            <div class="box round first grid">
                <h2>Tạo các cặp đấu cho vòng tiếp theo giải : <span style="color: #990000;"><%= championSelected.getName() %></span></h2>
                <div class="block">
                	<form name="formListMatch" method="post">
                		<input name="action" type="hidden" />
                		<input name="item_del" type="hidden" />
                		<% if( !"".equals(sMessageWarning) ) { %>
                        <div class="message warning">
                            <h5>Cảnh báo !</h5>
                            <p>
                                <%= sMessageWarning %>
                            </p>
                        </div>
                        <% } %>
                        <% if( !"".equals(sMessageOk) ) { %>
                        <div class="message success">
                            <h5>Success!</h5>
                            <p>
                                <%= sMessageOk %>
                            </p>
                        </div>
                        <% } %>
                        <% if( !"".equals(sMessageErr) ) { %>
                        <div class="message error">
                            <h5>Error!</h5>
                            <p>
                                <%= sMessageErr %>
                            </p>
                        </div>
                        <% } %>
                		<table class="data display datatable" style="margin: -10px auto;">
                			<tr>
                				<td style="width: 60%;">
                					<fieldset style="width: 100%; border: 1px solid #3366CC;">
			                			<legend style="margin-left: 15px;"><strong> Vòng đấu hiện tại </strong></legend>
			                			<table class="form" style="text-align: center;">
				                			<tr>
				                				<td>
				                					<a href="<%= request.getContextPath() %>/admin/tennis/champion/index.jsp">Giải đấu:</a>
				                					<select id="select" name="championCode" onchange='document.formListMatch.action.value="NOTHING";document.formListMatch.submit();'>
				                						<option value="0"> - Tất cả - </option>
				                						<%
													        //Lay ten cac giai -CODE1
															 //Cache cac GIAI DAU tren bo nho, tranh truy cap DB nhieu lan.
														     Collection cChampions = TennisBuffer.getChampionList();
															 if (cChampions == null) {
																cChampions = tennisChampionDAO.findChampionRunning();
															 }
													         if (cChampions != null && cChampions.size() > 0) {
													             TennisChampion champion = null;
													             String selected = "";
													             int i=0;
													             for(Iterator it = cChampions.iterator(); it.hasNext();i++){
													                 champion = (TennisChampion)it.next();
													                 if (champion == null) continue;
													                 //Show current code
													                 if (champion.getCode().equals(sChampionCode)) {
													                     selected="selected";
													                 } else{
													                     selected="";
													                 }
													         %>
													         	 <%--Gia tri nhan duoc sau khi submit form la championCode --%>
													        	 <option value="<%=champion.getCode()%>" <%=selected%>> <%=champion.getName()%></option>
													         <%
													            } //for
													         }//if
														%>
				                					</select>
				                					<a href="<%= request.getContextPath() %>/admin/tennis/champion/list-phase.jsp?championCode=<%= championSelected.getCode() %>&seasonId=<%= championSelected.getCurrentSeason() %>">Giai đoạn:</a>
				                					<select id="select" name="slbPhase" onchange='document.formListMatch.action.value="NOTHING";document.formListMatch.submit();'>
				                						<option value="0"> - Tất cả - </option>
				                						<%
				                						 if (championSelected != null) {
													         Collection cPhase = tennisPhaseDAO.findAll(championSelected.getCode(), championSelected.getCurrentSeason());
													         String selectedP = "";
													         TennisPhase phase = null;
													         if(cPhase != null && !cPhase.isEmpty()) {
														         for(Iterator it = cPhase.iterator(); it.hasNext();) {
														             phase = (TennisPhase) it.next();
														             if (phase == null) continue;
														             if(phase.getId().equals(phaseId)) {
														                 selectedP="selected";
														             } else {
														                 selectedP="";
														             }
												        %>
												              <option value="<%=phase.getId()%>" <%=selectedP%>> <%=phase.getPhaseName()%></option>
												        <%
												          	 	}//for
												          	 }//if
												          }//if
												        %>
				                					</select>
				                					<a href="<%= request.getContextPath() %>/admin/tennis/champion/list-round.jsp?phaseId=<%= championSelected.getCurrentPhase() %>">Vòng đấu:</a>
				                					<select id="select" name="slbRound">
				                						<option value="0"> - Tất cả - </option>
				                						<%
												         Collection cRounds = tennisRoundDAO.findAll(phaseId);
												         String selectedR = "";
												         TennisRound  round = null;
												         for(Iterator it = cRounds.iterator(); it.hasNext();) {
												             round = (TennisRound) it.next();
												              if (round == null) continue;
												              if(round.getRoundCode().equals(currRound)) {
												              	  currRoundNo = round.getRoundNo();
												                  selectedR="selected";
												              } else {
												                  selectedR="";
												              }
												        %>
												              <option value="<%=round.getRoundCode()%>" <%=selectedR%>> <%=round.getRoundCode()%></option>
												        <%
												          }//for
												        %>
				                					</select>
				     								<button type="button" onclick="document.formListMatch.action.value='FIND';document.formListMatch.submit();" class="btn btn-grey">Tìm kiếm</button>
				                				</td>
				                			</tr>
				                		</table>
			                		</fieldset>
                				</td>
                				<td style="padding-left: 10px;">
                					<fieldset style="width: 100%; border: 1px solid #3366CC;">
                						<legend style="margin-left: 15px;"><strong>Vòng đấu tiếp theo</strong></legend>
                						<table class="form" style="text-align: center;">
                							<tr>
                								<td>
                									<a href="<%= request.getContextPath() %>/admin/tennis/champion/list-round.jsp?phaseId=<%= championSelected.getCurrentPhase() %>">Vòng đấu:</a>
				                					<select id="select" name="slbNextRound"">
				                						<option value="0"> - Tất cả - </option>
				                						<%
												         for(Iterator it = cRounds.iterator(); it.hasNext();) {
												             round = (TennisRound) it.next();
												              if (round == null) continue;
												              if (round.getRoundNo() < currRoundNo + 1) continue;
												              if(sNextRound == null && round.getRoundNo() == currRoundNo + 1) {
												                  selectedR="selected";
												              } else if (round.getRoundCode().equals(sNextRound)) {
												              	  selectedR="selected";
												              } else {
												                  selectedR="";
												              }
												        %>
												              <option value="<%=round.getRoundCode()%>" <%=selectedR%>> <%=round.getRoundCode()%></option>
												        <%
												          }//for
												        %>
				                					</select>
				                					&nbsp;&nbsp;&nbsp;
                									<button type="button" onclick="document.formListMatch.action.value='CREATE_SCHEDULE';document.formListMatch.submit();" class="btn btn-grey">Tạo lịch</button>
                								</td>
                							</tr>
                						</table>
                					</fieldset>
                				</td>
                			</tr>
                		</table>
	                    <table class="data display datatable" id="example">
							<thead>
								<tr>
									<th class="header" style="width: 3%;">#</th>
									<th class="header" style="width: 5%;">Mã giải</th>
									<th class="header" style="width: 5%;">Vòng</th>
									<th class="header" style="width: 15%;">Tay vợt 1</th>
									<th class="header" style="width: 15%;">Tay vợt 2</th>
									<th class="header" style="width: 5%;">MAP_ID</th>
									<th class="header" style="width: 5%;">STT</th>
									<th class="header" style="width: 10%;text-align: center;">Thời gian</th>
									<th class="header" style="width: 3%;">Sửa</th>
									<th class="header" style="width: 3%;">Xóa</th>
								</tr>
							</thead>
							<tbody>
								<% 
									if(vMatch != null && !vMatch.isEmpty()) {
										TennisMatch match = null;
										int i = 0;
										String seasonName = "";
										TennisPlayer player1 = null;
										TennisPlayer player2 = null;
										DateTime matchDate = null;
										String lastMatchDate = "";
										
										for (Iterator it = vMatch.iterator(); it.hasNext(); i++) {
											match = (TennisMatch)it.next();
											if( match == null ) continue;
											player1 = (TennisPlayer) TennisBuffer.getPlayerFromId(match.getFirstPlayerId());
											player2 = (TennisPlayer) TennisBuffer.getPlayerFromId(match.getSecondPlayerId());
											matchDate = new DateTime(match.getMatchDate());
								            //if(!lastMatchDate.equals(matchDate.getDay()+"/"+matchDate.getMonth())){
								            //	lastMatchDate = matchDate.getDay()+"/"+matchDate.getMonth();
												// Chưa hiển thị
								            //}
								%>
								<tr class="eventt" <%= match.getIsMatchInv() == 1 ? "style=\"background-color: #FFCC99;\"":"" %>>
									<td align="center">
										<%= i+1 %>
										<input type="checkbox" name="chkID" value="<%=match.getId()%>" />
										<input type="hidden" name="txt_match_id" value="<%=match.getId()%>" />
									</td>
									<td align="center"><%= match.getChampionCodeSMS() %></td>
									<td align="center"><%= match.getRound() %></td>
									<td align="center"><%= player1 != null ? player1.getName():"" %></td>
									<td align="center"><%= player2 != null ? player2.getName():"" %></td>
									<td align="center"><%= (match.getMapMatchId() != null && match.getMapMatchId() != BigDecimal.ZERO) ? match.getMapMatchId():"Chưa có" %></td>
									<td align="center"><input tabindex="<%= i+1 %>" onchange="isExistedNumber(this);" size="2" type="text" name="txtSTT" value = "<%= match.getStt() %>" /></td>
									<td><%=(matchDate.getHour()+"h"+matchDate.getMinute()+"' ") +" "+ matchDate.getDay()+"/"+matchDate.getMonth()+"/" + matchDate.getYear()%></td>
									<td align="center">
										<a href="edit-match.jsp?id=<%= match.getId() %>">
											<img style="vertical-align: middle;" src="<%= request.getContextPath() %>/admin/tennis/img/cog.png" />
										</a>
									</td>
									<td align="center">
										<a href="javascript:void(0);" onclick="if(confirm('Bạn có chắc chắn muốn xóa ??? ')){f_delete_item(<%= match.getId() %>);}">
											<img style="vertical-align: middle;" src="<%= request.getContextPath() %>/admin/tennis/img/cross.png" />
										</a>
									</td>
								</tr>
								<% 
										}// for
									} // if
								%>
							</tbody>
						</table>
					</form>
					<br />
					<div style="display: block;">
						<button type="button" onclick="window.location.href='add-match.jsp?championCode=<%= sChampionCode %>';" class="btn btn-grey">Thêm</button>
						<button type="button" onclick="updateSTTMatch();" class="btn btn-grey">Update STT</button>
						<button type="button" onclick="if(confirm('Bạn có chắc chắn muốn xóa ??? ')){f_delete_select_item();}" class="btn btn-grey">Xóa</button>
					</div>
					<br />
					<br />
					<a class="condition"></a> &nbsp;&nbsp;&nbsp;<strong>Trận đấu điều kiện</strong> (trận đấu này được tạo để đặc cách cho 1 tay vợt vào thẳng vòng trong)
                </div>
            </div>
            <% 
            	} else { //end if championSelected != null 
           	%>
           	<div class="box round first grid">
                <h2>Tạo lịch thi đấu cho giải đấu</h2>
                <div class="block">
                	<div class="message warning">
                        <h5>Cảnh báo !</h5>
                        <p>
                            Không tồn tại giải đấu có code = <%= sChampionCode %>
                        </p>
                    </div>
              	</div>
            </div>
           	<% } %>
        </div>
        <div class="clear">
        </div>
    </div>
    <%@ include file="../include/footer.jsp" %>
</body>
</html>
<script language="JAVASCRIPT">
	function isExistedNumber(abc) {
		//alert('length='+formListMatch.elements['txtSTT'].length);
  		for (var i=0; i < formListMatch.elements['txtSTT'].length; i++) {
     		var e = formListMatch.elements['txtSTT'][i];
	     	if(e.value == abc.value && e.tabIndex != abc.tabIndex){
	     		alert('Thứ tự trận đấu đã bị trùng');
	     		return false;
	     	}
	  	}
	}
	function checkExistedNumber() {
  		for (var i=0; i < formListMatch.elements['txtSTT'].length; i++) {
     		var e = formListMatch.elements['txtSTT'][i];
     		for (var j=0; j < formListMatch.elements['txtSTT'].length; j++) {
				var e1 = formListMatch.elements['txtSTT'][j];
				//console.log(e.value+"-"+e1.value);
		     	if(e.value == e1.value && e.tabIndex != e1.tabIndex){
		     		alert('Thứ tự trận đấu đã bị trùng ');
		     		return false;
		     	}
	     	}
	  	}
	  	return true;
	}
	function updateSTTMatch(){
		if(checkExistedNumber()){
			document.formListMatch.action.value="UPDATE_STT";
			document.formListMatch.submit();
		}
	}
</script>